package com.woniu.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class OrderLimitRoutePredicateFactory extends AbstractRoutePredicateFactory<OrderLimitRoutePredicateFactory.Config> {


    public OrderLimitRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minPid", "maxPid", "minCount", "maxCount");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String path = serverWebExchange.getRequest().getURI().getPath();
                String[] split = path.split("/");
                Integer pid = Integer.parseInt(split[split.length - 2]);
                Integer count = Integer.parseInt(split[split.length - 1]);
                if(pid >= config.getMinPid() && pid <= config.getMaxPid() && count >= config.getMinPid() && count <= config.getMaxCount()){
                    return true;
                }
                return false;
            }
        };
    }

    public static class Config{
        int minPid;
        int maxPid;
        int minCount;
        int maxCount;

        public int getMinPid() {
            return minPid;
        }

        public void setMinPid(int minPid) {
            this.minPid = minPid;
        }

        public int getMaxPid() {
            return maxPid;
        }

        public void setMaxPid(int maxPid) {
            this.maxPid = maxPid;
        }

        public int getMinCount() {
            return minCount;
        }

        public void setMinCount(int minCount) {
            this.minCount = minCount;
        }

        public int getMaxCount() {
            return maxCount;
        }

        public void setMaxCount(int maxCount) {
            this.maxCount = maxCount;
        }
    }

}
